package stancel.peter.smartsilencer.background;

import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import stancel.peter.smartsilencer.Event;
import stancel.peter.smartsilencer.SmartSilencer;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

/**
 * Najhlavnejsia cast aplikacie, riadi spravu vytvorenych udalosti. Obsahuje GPS
 * a orientacne listenery, ktore su potrebne pre zistenie, ci su splnene
 * kriteria polohy alebo orientacie.
 * @author Peter Stancel
 */
public class CheckingService extends Service {

	/**
	 * Spusta vlakno na kontrolu udalosti.
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		SmartSilencer smartSilencer = (SmartSilencer) getApplication();
		List<Event> list = smartSilencer.loadFromFile();
		int ringerMode = AudioManager.RINGER_MODE_NORMAL;
		AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		boolean airplaneMode = false;

		for (int i = 1; i <= list.size(); i++) {
			// Najvacsiu prioritu maju udalosti na konci listu.
			Event event = list.get(list.size() - i);
			if (event.isTurnOn() && checkTime(event, event.getDays())) {
				if (event.isVibration()) {
					ringerMode = AudioManager.RINGER_MODE_VIBRATE;
				} else{
					ringerMode = AudioManager.RINGER_MODE_SILENT;
				}
				airplaneMode = event.isAirplaneMode();
				break;
			}
		}

		audioManager.setRingerMode(ringerMode);

		boolean isEnabled = Settings.System.getInt(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;
		if (isEnabled != airplaneMode) {
			isEnabled = airplaneMode;
			Settings.System.putInt(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, airplaneMode ? 1 : 0);
			Intent airplaneIntent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
			airplaneIntent.putExtra("state", airplaneMode);
			sendBroadcast(airplaneIntent);
		}

		removeEvents(list);
		smartSilencer.saveListToFile(list);
		
		if(intent.getBooleanExtra("smartsilencer_alarmservice", true)){
			Log.i("CheckingService", "Spustenie AlarmService");
			startService(new Intent(this, AlarmService.class));
		}
		
		Log.i("CheckingService", "ThreadLoop");
		stopSelf();
		return START_STICKY;
	}

	/**
	 * Vymaze udalosti kalendara, ktore sa uz stali.
	 */
	private void removeEvents(List<Event> list) {
		Iterator<Event> iterator = list.iterator();
		while (iterator.hasNext()) {
			Event event = iterator.next();
			if(event.isOnetime()){
				Calendar date = Calendar.getInstance();
				int time = date.get(Calendar.HOUR_OF_DAY) * 100 + date.get(Calendar.MINUTE);
				if (event.getDateEnd() <= time) {
					iterator.remove();
				}
			}
		}
	}

	/**
	 * Testuje, ci je splnene casove kriterium.
	 * @param event udalost
	 * @param days dni, kedy ma byt aktivovana udalost
	 * @return true aj je splnene casove kriterium, false ak nie je
	 */
	private boolean checkTime(Event event, boolean[] days) {
		Calendar calendar = Calendar.getInstance();
		int day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		if (days != null) {
			int currentTime = calendar.get(Calendar.HOUR_OF_DAY) * 100 + calendar.get(Calendar.MINUTE);
			if (event.isNextDay()) {
				if (days[day] && event.getDateStart() <= currentTime || currentTime < event.getDateEnd()) {
					return true;
				} else if (days[((day + 7) - 1) % 7] && currentTime < event.getDateEnd()) {
					return true;
				}
			} else if (event.getDateStart() <= currentTime && currentTime < event.getDateEnd()) {
				return days[day];
			}
		}
		return false;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}